<template>
  <view>
    <view class="addressWrapper u-flex">
      <view class="btn" @click="chooseAddress" v-if="!address">选择地址</view>
      <view class="addressInfo" v-else>
        <view class="address">{{ address }}</view>
        <view class="user">{{ user }}</view>
      </view>
    </view>
    <!-- 商品列表 -->
    <view
      class="goodsItem u-flex"
      v-for="item in checkedGoodsList"
      :key="item.goods_id"
    >
      <!-- 图片 -->
      <view>
        <u-image :src="item.pic" width="190" height="190" />
      </view>

      <view class="info u-flex">
        <!-- 商品标题 -->
        <view>{{ item.goods_name }}</view>
        <view class="bottom u-flex">
          <!-- 商品价格 -->
          <view class="price">￥{{ item.goods_price }}</view>
          <!-- 商品数量 -->
          <view class="number u-flex">
            <view class="num">数量：{{ item.number }}</view>
          </view>
        </view>
      </view>
    </view>
    <view class="cartBottom u-flex">
      <view class="totalPrice u-flex-1">
        合计：<text class="price">￥{{ totalPrice }}</text></view
      >
      <view class="submitBtn" @click="handlePayment"
        >去支付({{ totalGoodsNumber }})
      </view>
    </view>
  </view>
</template>

<script>
import { mapGetters, mapMutations, mapState, mapActions } from 'vuex';
export default {
  data() {
    return {
      address: '',
      user: '',
    };
  },
  computed: {
    ...mapState('user', ['token']),
    ...mapGetters('cart', [
      'totalGoodsNumber',
      'totalPrice',
      'checkedGoodsList',
    ]),
  },
  methods: {
    ...mapActions('user', ['wxLogin']),
    ...mapMutations('cart', ['clearCartAfterPayment']),

    //   获取地址：uni.chooseAddress()
    async chooseAddress() {
      const [err, res] = await uni.chooseAddress();
      if (!err) {
        this.address = `${res.provinceName}${res.cityName}${res.countyName}${res.detailInfo}${res.nationalCode}`;
        this.user = `${res.userName}${res.telNumber}`;
      }
    },

    // 获取登录信息uni.login()、获取用户信息uni.getUserProfile({desc描述：必填})，发送请求到后台，返回token值
    // async wxLogin() {
    //   const [errProfile, resProfile] = await uni.getUserProfile({ desc: '为' });
    //   const [errLogin, resLogin] = await uni.login();
    //   if (!errProfile && !errLogin) {
    //     const { encryptedData, rawData, iv, signature } = resProfile;
    //     const { code } = resLogin;
    //     const res = await this.$u.post('/users/wxlogin', {
    //       encryptedData,
    //       rawData,
    //       iv,
    //       signature,
    //       code,
    //     });
    //     const { token } = res.message;
    //     console.log(token);
    //     return token;
    //   } else {
    //     uni.showToast({
    //       title: '登录失败，支付取消。需重新登录',
    //       icon: 'none',
    //     });
    //   }
    // },

    // 创建订单，根据后台文档重构数据，发送请求到后台，返回订单编号
    async createOrder() {
      const data = {
        order_price: this.totalPrice,
        consignee_addr: `${this.address} ${this.user}`,
        goods: this.checkedGoodsList.map((item) => {
          return {
            goods_id: item.goods_id,
            goods_number: item.number,
            goods_price: item.goods_price,
          };
        }),
      };
      //   声明订购为异步的发送请求到/my/orders/create，打包好的data数据，使用token授权
      const res = await this.$u.post('/my/orders/create', data);
      return res.messgae.order_number;
    },

    // 合集大成：如果没有地址的处理。有地址之后
    async handlePayment() {
      if (!this.address) {
        uni.showToast({ title: '请提供发货地址', icon: 'none' });
        return;
      }
      if (!this.token) {
        await this.wxLogin();
      }
      const order_number = await this.createOrder();
      const pay = await this.createPayment(order_number);
      const [errPay, resPay] = await uni.requestPayment(pay);
      if (!errPay) {
        uni.showToast({ title: '付款成功，跳转回购物车页面', icon: 'none' });
        console.log(resPay);
        this.clearCartAfterPayment();
        uni.switchTab({ url: '/pages/cart/cart' });
      }
    },

    // 创建账单
    async createPayment(order_number) {
      const data = { order_number };
      const res = await this.$u.post('/my/orders/req_unifiedorder', data);
      return res.message.pay;
    },
  },
};
</script>

<style lang="scss" scoped>
.cartBottom {
  padding: 34rpx;
  position: fixed;
  left: 0;
  bottom: 0;
  width: 100%;
  background: #fdfdfd;
  border: 1px #aea9a9 solid;
  .totalPrice {
    font-weight: bolder;
    font-size: 26rpx;
    margin-left: 15rpx;
    .price {
      font-weight: bolder;
      font-size: 32rpx;
      color: red;
    }
  }
  .submitBtn {
    background: orangered;
    line-height: 52rpx;
    padding: 0 26rpx;
    border-radius: 26rpx;
    color: white;
    font-size: 32rpx;
    height: 52rpx;
  }
}
.addressWrapper {
  padding: 70rpx 20rpx;
  height: 250rpx;
  border-bottom: 10px solid #f9f9f9;
  align-items: center;
  justify-content: center;
  .addressInfo {
    width: 100%;
    padding: 0 30rpx;
    font-size: 32rpx;
    color: #434343;
    .user {
      font-size: 26rpx;
      margin-top: 20rpx;
    }
  }
  .btn {
    width: 302rpx;
    color: red;
    text-align: center;
    border-radius: 45rpx;
    line-height: 90rpx;
    border: 3rpx solid red;
  }
}
.goodsItem {
  margin: 20rpx 5rpx;
}
.info {
  flex: 1;
  margin-left: 20rpx;
  flex-direction: column;
  height: 190rpx;
  padding: 26rpx 0;
  justify-content: space-between;
  .top {
    width: 100%;
    font-size: 24rpx;
  }
  .bottom {
    width: 100%;
    justify-content: space-between;
    .price {
      color: red;
      font-size: 35rpx;
      font-weight: bold;
    }
    .number {
      font-size: 35rpx;
      .num {
        margin: 0 10rpx;
      }
    }
  }
}
</style>
